import { reqAddressEdit,reqAddressDetail,reqAddressDelete } from "../../api/addressedit";
import { modal } from "../../utils/extendApi";

Page({
  data: {
    consignee:'',
    phone:'',
    state:'',
    city:'',
    district:'',
    streetAddress:'',
    isDefault:'',
    addressId:''
  },

  onAddressChange(event){
    //  console.log(event);
    const [state,city,district]= event.detail.value;
    
    this.setData({
      state,
      city,
      district
    })
  },

  onLoad: function(options) {
    const addressId = options.id; // 获取传递的 id
    // console.log(addressId);
    if (addressId) {
      this.setData({
        addressId:addressId
      })
      this.loadAddressById(addressId);
    }
  },


  async loadAddressById(addressId) {
    const {data} = await reqAddressDetail(addressId)
    this.setData({
      consignee:data.consignee,
      phone:data.phone,
      state:data.state,
      city:data.city,
      district:data.district,
      streetAddress:data.streetAddress,
      isDefault:data.default
    });
  },

  async saveAddress(){

    const param = {
      addressId:this.data.addressId,
      consignee:this.data.consignee,
      phone:this.data.phone,
      state:this.data.state,
      city:this.data.city,
      district:this.data.district,
      streetAddress:this.data.streetAddress,
      default:this.data.isDefault
    }
    const {code} = await reqAddressEdit(param)
    if (code===1){
      wx.navigateBack()
      wx.toast({title:'地址修改成功',icon:'success'})
    }else{
      wx.toast({title:'地址修改失败',icon:'error'})
    }

  },

  isdefaultchange() {
    // 获取当前 isDefault 的值
    const currentIsDefault = this.data.isDefault;
    
    // 根据当前值设置 instance 的新值
    let instance = !currentIsDefault;
    //  console.log(instance);
    
    // 如果需要更新 data 中的 isDefault 值，可以这样做
    this.setData({
      isDefault: instance
    });
  },

   async deleteaddress(){
    const addressId=this.data.addressId
    const {code} = await reqAddressDelete(addressId)
    if (code===1){
      wx.navigateBack()
      wx.toast({title:'删除成功',icon:'success'})
    }else{
      wx.toast({titke:'删除失败',icon:'error'})
    }

   },

   async ensuredelete(){
    const defalut = this.data.isDefault;
    if(defalut){
      wx.modal({content:'无法删除默认地址',
      showCancel:false})
      return
    }

    const res = await wx.modal({content:'确认删除地址？'})
    if (res) {
      this.deleteaddress()
    } 
   }
});